﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Brain.Editor
{
    /// <summary>
    /// TODO: This class should be abstract, Database itself shouldn't be used
    /// </summary>
    public class Database : IBrainSonSerialiable
    {
        public List<IGameVariable> Variables;

        public bool ShouldSerialize { get; set; }

        public Database()
        {
            Variables = new List<IGameVariable>();
            ShouldSerialize = true;
        }

        public virtual void NewVariable()
        {

        }

        public virtual void RemoveVariable(IGameVariable var)
        {
            this.Variables.Remove(var);
        }

        public virtual void SerializeData(SerializationData parentData, string index)
        {
            parentData.AddData("Database.Var", this.Variables.Count, index);
            string add = index.ToString();
            for (int i = 0; i < this.Variables.Count; i++)
            {
                IGameVariable variable = this.Variables[i];
                Type t = variable.GetType();
                parentData.AddData("Database.VarType" + add + i, t.FullName);
                parentData.AddData("Database.VarAss" + add + i, t.Assembly.GetName().Name);


                variable.SerializeData(parentData, add + i);
            }
        }

        public virtual void DeserializeData(SerializationData parentData, string index)
        {
            int vars = parentData.GetData<int>("Database.Var", index);
            this.Variables = new List<IGameVariable>(vars);
            string add = index.ToString();

            for (int i = 0; i < vars; i++)
            {
                string type = parentData.GetData<string>("Database.VarType" + add + i);
                string ass = parentData.GetData<string>("Database.VarAss" + add + i);

                Assembly asse = Assembly.Load(new AssemblyName(ass));
                Type t = asse.GetType(type);

                IGameVariable variable = (IGameVariable)Activator.CreateInstance(t);
                variable.DeserializeData(parentData, add + i);

                this.Variables.Add(variable);
            }
        }


        public void DeserializedAll()
        {
        }
    }
}
